/**
 * @file
 * @auth jinguangguo
 * @date 2017/1/18
 */

import Vue from 'vue';
import tpl from './tpl.html';
import commonService from '../../../common/commonService';
import symbolConfig from '../../../common/symbolConfig';
import service from './service';
import util from './util';
import CONFIG from './config';
import parseUrl from '../../../../grsc-base/util/parseUrl';

import filter from '../../../../grsc-base/util/filter';
import lib from '../../../common/lib';
import Popover from '../../../../grsc-base/component/Popover.vue';
import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue';
import Pager from '../../../../grsc-base/component/Pager.vue';
import Qrcode from '../../../../grsc-base/component/Qrcode.vue';
import MathTool from '../../../../grsc-base/util/mathtool';

import {PAGE_SIZE} from '../../../../grsc-base/common/constants.js';

const BASE_UID_NO = 100000;

export default Vue.extend({
    name: "MyOrder",
    template: tpl,
    components: {
        Popover,
        Qrcode,
        Loading,
        NoData,
        Pager
    },

    data() {
        return {
            CONFIG: CONFIG,
            filter: filter,

            isLoading: true,

            symbols: {},

            tradeList: {
                list: [],
                isLoading: false,
                pageNo: 1,
                pageNum: 0
            },
            tradeHistoryList: {
                list: [],
                isLoading: false,
                pageNo: 1,
                pageNum: 0
            },

            tradeType: null,
            symbol: null,
            coinPrecision: null,
            highlightNo: null,
            amountPrecision: null,
            coinText: null
        }
    },
    created() {

        /*
        this.realAuthDetection();
        this.fetchIP();
        this.fetchIPlog();
        this.queryGoogleStatus();*/

        this.isLoading = true;
        commonService.fetchSymbols((symbolMap, symbolList) => {
            this.isLoading = false;
            this.symbols = symbolMap;
            this.selectCoin(this.symbols[Object.keys(this.symbols)[0]]);    //默认选择第一个
        });
        //this.fetchTradeList();
    },
    mounted(){
    },
    methods: {
        selectCoin(item) {
            let symbol = item.symbol;   //此symbol用于币种单位文案和键值，与config中的键值一致

            this.symbol = item.symbol;  //此symbol用于选中样式，与config中的symbol一致

            let currentSymbol = this.symbols[symbol];

            this.tradeType = currentSymbol.assetCode2;
            this.coinPrecision = currentSymbol[symbolConfig.PRICEPRECISION];
            this.highlightNo = currentSymbol[symbolConfig.HIGHLIGHTNO];
            this.amountPrecision = currentSymbol[symbolConfig.AMOUNTPRECISION];

            let coin = symbol.split('_')[1];
            this.coinText = coin;

            this.tradeList.list = [];
            this.tradeList.pageNo = 1;
            this.tradeList.pageNum = 0;

            this.fetchTradeList();
            this.fetchTradeHistoryList();
        },
        fetchTradeList() {
            this.tradeList.isLoading = true;

            let pageSize = PAGE_SIZE;
            service.tradeCoinCurrentList({
                symbol: this.symbol,
                pageNo: this.tradeList.pageNo,
                pageSize: pageSize
            }).done((rep) => {
                this.tradeList.isLoading = false;
                if (rep.code == window.CODE.SUCCESS) {
                    this.tradeList.list = this._getFormattedTradeList(rep.data.list);
                    this.tradeList.pageNum = rep.data.pageNum;
                    // 如果当前页内容为空, 返回上一页
                    if (this.tradeList.list.length === 0) {
                        if(this.tradeList.pageNo>1){
                            this.tradeList.pageNo--;
                            this.fetchTradeList();
                        }
                    }
                } else if(rep.code == window.CODE.NO_LOGIN.CODE){

                } else{
                    window.error(rep.msg);
                }
            }).fail((rep) => {

            });
        },
        changeTradePage(pageNo) {
            this.tradeList.pageNo = pageNo;
            this.fetchTradeList()
        },

        /**
         * 格式化列表数据
         * @param list
         * @returns {*}
         * @private
         */
        _getFormattedTradeList(list) {
            if (list.length === 0) {
                return [];
            }

            let that = this;
            $.map(list, (item, index) => {
                // 日期
                // item.createDateHtml = util.getDateHtml(item.createDate);
                // 类型
                item.tradeCoinTypeHtml = util.getTradeTypeHtml(item.tradeCoinType);

                // 市价
                if (item.tradeCoinFlag === CONFIG.TRADE_FLAG_MARKET.KEY) {
                    item.priceText = 'Market Price';
                    if (item.tradeCoinType == CONFIG.TRADE_TYPE_SELL.KEY) {
                        // 委托数量
                        item.numberHtml = `${filter.floorFix(item.number,that.amountPrecision)} ${that.coinText}`;
                        // 成交数量 - 果仁
                        // item.tradedCoinHtml = `<i class="icon icon-g"></i>${filter.floorFix(item.tradedCoin)}`;
                        // 剩余数量 - 果仁
                        item.numberOverHtml = `${filter.floorFix(item.numberOver,that.amountPrecision)} ${that.coinText}`;
                    } else {
                        // 委托数量
                        item.numberHtml = `${filter.floorFix(item.money, this.coinPrecision) +' '+ that.symbol.split('_')[0]} `;
                        // 成交数量 - currencyout
                        // item.tradedCoinHtml = `￥${filter.floorFix(item.totalTraded)}`;
                        // 剩余数量 - currencyout
                        item.numberOverHtml = `${filter.floorFix(item.moneyOver)  +' '+ that.symbol.split('_')[0] }`;
                    }
                } else {    // 限价
                    item.priceText = filter.floorFixPrice(item.price, this.coinPrecision) + ' ' + that.symbol.split('_')[0];
                    // 委托数量
                    item.numberHtml = `${filter.floorFix(item.number,that.amountPrecision)} ${that.coinText}`;
                    // 成交数量
                    item.tradedCoinHtml = `${filter.floorFix(MathTool.reduce(item.number, item.numberOver),that.amountPrecision)} ${that.coinText}`;
                    // 剩余数量
                    item.numberOverHtml = `${filter.floorFix(item.numberOver,that.amountPrecision)} ${that.coinText}`;
                }
            });
            return list;
        },
        cancelOrder(item, $event) {
            let that = this;
            window.confirm({
                target: $event.target,
                content: that.$t('myOrder.areYouSure'),
                confirmBtnText:that.$t('common.yes'),
                cancelBtnText:that.$t('common.no'),
            }).done(() => {
                service.tradeCoinCancelByid({
                    symbol: this.symbol,
                    orderNo: item.payTransactionNo
                }).done(rep => {
                    if (rep.code === window.CODE.SUCCESS) {
                        this.fetchTradeList();
                        // 更新资产数据
                        $(document).trigger('$$assets');
                    } else {
                        if (rep.code === window.CODE.ORDER_BIND_HAS_SUCCESS.CODE) {
                            window.error(window.CODE.ORDER_BIND_HAS_SUCCESS[this.$i18n.locale], () => {
                                this.fetchTradeList();
                            });
                        } else if (rep.code === window.CODE.ORDER_CANCEL.CODE) {
                            window.error(window.CODE.ORDER_CANCEL[this.$i18n.locale], () => {
                                this.fetchTradeList();
                            });
                        } else {
                            window.error(rep.msg);
                        }
                    }
                });
            }).fail(() => {

            });
        },

        /**
         * 获取交易历史数据列表
         */
        _initDetailById(list) {
            let query = parseUrl();
            if (query.id) {
                let id = query.id;
                let item = _.find(list, {
                    id: +id
                });
                //this.toggleDetail(item);
            }
        },

        /**
         * 获取数据列表
         */
        fetchTradeHistoryList() {
            this.tradeHistoryList.isLoading = true;
            let pageSize = PAGE_SIZE;
            service.tradeCoinHistoryList({
                symbol: this.symbol,
                pageNo: this.tradeHistoryList.pageNo,
                pageSize: pageSize
            }).done((rep) => {
                this.tradeHistoryList.isLoading = false;
                if (rep.code == window.CODE.SUCCESS) {
                    this.tradeHistoryList.list = this._getFormattedTradeHistoryList(rep.data.list);
                    this.tradeHistoryList.pageNum = rep.data.pageNum;
                    if (this.tradeHistoryList.list.length > 0) {
                        this._initDetailById(this.list);
                    }
                } else {
                    window.error(rep.msg);
                }
            }).fail((rep) => {

            });
        },
        
        changeTradeHistoryListPage(pageNo) {
            this.tradeHistoryList.pageNo = pageNo;
            this.fetchTradeHistoryList()
        },

        _getFormattedTradeHistoryList(list) {
            let that = this;

            $.map(list, function (item, index) {
                // // 日期
                // item.createDateHtml = util.getDateHtml(item.createTime);
                // 类型
                item.tradeCoinTypeHtml = util.getTradeTypeHtml(item.tradeCoinType);

                // 平均价
                setAveragePrice(item);

                // 初始化交易详情
                item.detail = null;
            });
            return list;

            /**
             * 设置平均价
             * @param item
             */
            function setAveragePrice(item) {
                item.tradedCoin = MathTool.reduce(item.number, item.numberOver);

                if (item.tradedCoin <= 0) {
                    item.averagePrice = 0;
                } else {
                    item.averagePrice = item.matchedMoney / item.tradedCoin;
                    // console.log('item.averagePrice:' + item.averagePrice);
                }
            }

        }
    },
    watch: {}
});
